<template>
  <div class="login">
    <div class="login-box">
      <el-form
        ref="loginFormRef"
        :rules="loginFormrules"
        :model="loginForm"
        label-width="80px"
        style="width: 400px"
      >
        <el-form-item label="账号" prop="username">
          <el-input
            v-model="loginForm.username"
            prefix-icon="el-icon-s-custom"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            prefix-icon="el-icon-lock"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label-width="0px" class="btns">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="warning">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import { loginApi } from '@/api/index.js'

export default {
  data () {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      loginFormrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度不能小于3位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度不能小于3位', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login () {
      this.$refs.loginFormRef.validate(async (valid) => {
        if (valid) {
          // this.$message.success("登录成功");
          console.log(valid, 'sadasd ')

          const res = await loginApi(this.loginForm) // await loginApi(); 这个返回值  赋值给res了
          console.log(res)

          const token = res.data.token // 那么应该res.token

          // 存储token到localStorage;
          localStorage.setItem('token', token)

          // 跳转到首页或其他页面;
          this.$router.push('/home')
        } else {
          this.$message.error('登录失败')
        }
      })
    }
  }
}
</script>
<style>
.login {
  height: 100%;
  width: 100%;
  background: #2b4b6b;
  display: flex;
  justify-content: center;
  align-items: center;
}
.login-box {
  width: 450px;
  height: 300px;
  background: #fff;
  display: flex;
  align-items: center;
}
.btns {
  display: flex;
  justify-content: center;
}
</style>
